package com.baseframe.sys.service.impl;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baseframe.common.utils.PageUtils;
import com.baseframe.sys.entity.FrameCodeItem;
import com.baseframe.sys.entity.FrameCodeMain;
import com.baseframe.sys.service.IFrameCodeService;
import com.baseframe.sys.service.dao.FrameCodeItemRepository;
import com.baseframe.sys.service.dao.FrameCodeMainRepository;

@Service("frameCodeService")
@Transactional
public class FrameCodeServiceImpl implements IFrameCodeService {

    @PersistenceContext
    private EntityManager em;
    @Autowired
    private FrameCodeMainRepository frameCodeMainRepository;
    @Autowired
    private FrameCodeItemRepository frameCodeItemRepository;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String name = (String) params.get("codeName");
        int pageSize = Integer.parseInt((String) params.get("limit"));
        int page = Integer.parseInt((String) params.get("page"));
        String sidx = (String) params.get("sidx");
        String order = (String) params.get("order");

        int total = Integer.parseInt(em.createNativeQuery("SELECT COUNT(1) FROM FRAME_CODE_MAIN  T WHERE 1=1").getSingleResult()
                .toString());

        StringBuffer listSql = new StringBuffer("select * from frame_code_main where 1=1");
        if (StringUtils.isNotBlank(name)) {
            listSql.append(" and codename like '%").append(name).append("%'");
        }

        if (sidx != null && !sidx.equals("")) {
            listSql.append(" order by ").append(sidx).append(" ").append(order);
        }

        List<FrameCodeMain> list = em.createNativeQuery(listSql.toString(), FrameCodeMain.class)
                .setFirstResult((page - 1) * pageSize)
                .setMaxResults(page * pageSize).getResultList();


        return new PageUtils(list, total, pageSize, page);
    }

    @Override
    public List<FrameCodeItem> queryItemList(Map<String, Object> params) {
        String codeGuid = (String) params.get("codeGuid");
        String sidx = (String) params.get("sidx");
        String order = (String) params.get("order");

        StringBuffer listSql = new StringBuffer("SELECT * FROM FRAME_CODE_ITEM WHERE 1=1");

        if (StringUtils.isNotBlank(codeGuid)) {
            listSql.append(" and codeguid = '").append(codeGuid).append("'");
        }

        if (sidx != null && !sidx.equals("")) {
            listSql.append(" order by ").append(sidx).append(" ").append(order);
        }else{
            listSql.append(" order by ordernumber desc,itemtext desc");
        }

        List<FrameCodeItem> frameCodeItemList = em.createNativeQuery(listSql.toString(), FrameCodeItem.class).getResultList();


        return frameCodeItemList;
    }

    @Override
    public int deleteBatchIds(List<String> codeGuids) {
        //删除子项
        try {
            codeGuids.forEach(codeGuid -> {
                frameCodeItemRepository.deleteByCodeguid(codeGuid);
                frameCodeMainRepository.deleteByCodeguid(codeGuid);
            });

            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        }
    }

    @Override
    public FrameCodeMain findByCodeName(String codeName) {
        return frameCodeMainRepository.findCountByCodename(codeName);
    }

    @Override
    public FrameCodeItem findByItemtextAndItemvalueAndCodeguid(String itemText, String itemValue, String codeGuid) {
        return frameCodeItemRepository.findByItemtextAndItemvalueAndCodeguid(itemText, itemValue, codeGuid);
    }

    @Override
    public int insert(Object obj) {
        try {
            if (obj instanceof FrameCodeMain) {
                frameCodeMainRepository.save((FrameCodeMain) obj);
            } else if (obj instanceof FrameCodeItem) {
                frameCodeItemRepository.save((FrameCodeItem) obj);
            }
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        }
    }

    @Override
    public int deleteItems(List<String> itemGuids) {
        try {
            itemGuids.forEach(itemGuid -> {
                frameCodeItemRepository.delete(itemGuid);
            });
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        }
    }

    @Override
    public int saveAll(List<FrameCodeItem> frameCodeItemList) {
        try {
            frameCodeItemList.forEach(frameCodeItem ->
                    frameCodeItemRepository.save(frameCodeItem)
            );
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        }
    }
}
